package org.jeecg.modules.generator.service.impl;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.generator.entity.*;
import org.jeecg.modules.generator.mapper.SysGenerateTabMapper;
import org.jeecg.modules.generator.service.*;
import org.jeecg.modules.generator.utils.CodeGenerateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @Description 系统表模版生成表服务
* @Author yangfeng
* @Date 2020-03-26 13:08:07
*/
@Service
public class SysTabGeneratedServiceImpl extends ServiceImpl<SysGenerateTabMapper, SysGenerateTab> implements SysGeneratedTabService {

    @Autowired
    private SysGenerateFieldInfoService generateFieldInfoService;

    @Autowired
    private SysGenerateItemConfigService generateItemConfigService;

    @Autowired
    private SysGenerateDatabaseConfigService sysGenerateDatabaseConfigService;

    @Autowired
    private SysGenerateTabColumnService sysGenerateTabColumnService;

    @Autowired
    private CodeGenerateUtils codeGenerateUtils;


    @Transactional
    @Override
    public Result addTbleInfo(String tableName, String systemId, String dataSourceId) {
        try {
            SysGenerateDatabaseConfig sysGenerateDatabaseConfig = sysGenerateDatabaseConfigService.getById(dataSourceId);
            Map<String, Object> map = codeGenerateUtils.isTableExists(tableName, sysGenerateDatabaseConfig);
            if ((Boolean) map.get("exist")) {
                SysGenerateTab generateEntity = (SysGenerateTab) map.get("table");
                List<SysGenerateTabColumn> sysGenerateTabColumnList = codeGenerateUtils.getColumnListByTableName(generateEntity.getTableName(), generateEntity.getPrimaryName(), sysGenerateDatabaseConfig);
                sysGenerateTabColumnService.saveBatch(sysGenerateTabColumnList);
                List<String> fieldList = sysGenerateTabColumnList.stream().map(sysGenerateTabColumn -> sysGenerateTabColumn.getFieldName()).collect(Collectors.toList());
                if (fieldList.contains("createBy") && fieldList.contains("createTime") && fieldList.contains("updateBy") && fieldList.contains("updateTime")) {
                    generateEntity.setWithOperate("1");
                } else {
                    generateEntity.setWithOperate("0");
                }
                generateEntity.setSystemId(systemId);
                generateEntity.setDataSourceId(dataSourceId);
                this.save(generateEntity);
                List<SysGenerateItemConfigEntity> tbGenerateItemConfigEntityList  = generateItemConfigService.list();
                List<SysGenerateFieldInfoEntity> generateFieldInfoEntityList = new ArrayList<>();
                for (SysGenerateTabColumn sysGenerateTabColumn : sysGenerateTabColumnList) {

                    /**设置字段的属性类型*/
                    SysGenerateFieldInfoEntity remarkInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),1);
                    remarkInfoEntity.setFieldItemName("columnComment");
                    remarkInfoEntity.setFieldItemRemark("字段含义");
                    /**字段属性类型页面属性*/
                    remarkInfoEntity.setRequired("1");  //必填
                    remarkInfoEntity.setValueType("1"); //文本框
                    remarkInfoEntity.setFieldItemValue(String.valueOf(sysGenerateTabColumn.getColumnComment())); //必填默认值（取数据库配置）
                    generateFieldInfoEntityList.add(remarkInfoEntity);

                    /**设置必填属性*/
                    SysGenerateFieldInfoEntity requiredInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),2);
                    requiredInfoEntity.setFieldItemName("required");
                    requiredInfoEntity.setFieldItemRemark("参与必填");
                    /**必填页面属性*/
                    requiredInfoEntity.setRequired("1");  //必填
                    requiredInfoEntity.setValueType("3"); //单选形式
                    requiredInfoEntity.setDictType("required_type");
                    requiredInfoEntity.setFieldItemValue(sysGenerateTabColumn.getRequired()); //必填默认值（取数据库配置）
                    generateFieldInfoEntityList.add(requiredInfoEntity);

                    /**设置字段默认值属性 */
                    SysGenerateFieldInfoEntity defaultInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),3);
                    defaultInfoEntity.setFieldItemName("defaultValue");
                    defaultInfoEntity.setFieldItemRemark("默认值");
                    /**字段默认值页面属性*/
                    defaultInfoEntity.setRequired("0");  //必填
                    defaultInfoEntity.setValueType("1"); //文本框
                    defaultInfoEntity.setFieldItemValue(sysGenerateTabColumn.getDefaultValue()); //必填默认值（取数据库配置）
                    generateFieldInfoEntityList.add(defaultInfoEntity);

                    /**设置字段长度属性 */
                    SysGenerateFieldInfoEntity lengthInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),4);
                    lengthInfoEntity.setFieldItemName("length");
                    lengthInfoEntity.setFieldItemRemark("值最大长度");
                    /**字段长度页面属性*/
                    lengthInfoEntity.setRequired("1");  //必填
                    lengthInfoEntity.setValueType("1"); //文本框
                    lengthInfoEntity.setFieldItemValue(String.valueOf(sysGenerateTabColumn.getColumSize())); //必填默认值（取数据库配置）
                    generateFieldInfoEntityList.add(lengthInfoEntity);

                    /**设置字段的属性类型*/
                    SysGenerateFieldInfoEntity javaTypeInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),5);
                    javaTypeInfoEntity.setFieldItemName("columnType");
                    javaTypeInfoEntity.setFieldItemRemark("属性类型");
                    /**字段属性类型页面属性*/
                    javaTypeInfoEntity.setRequired("1");  //必填
                    javaTypeInfoEntity.setValueType("1"); //文本框
                    javaTypeInfoEntity.setFieldItemValue(String.valueOf(sysGenerateTabColumn.getColumnType())); //必填默认值（取数据库配置）
                    generateFieldInfoEntityList.add(javaTypeInfoEntity);


                    /**设置是否为主键*/
                    if (StringUtils.isNotEmpty(sysGenerateTabColumn.getIsPrimaryKey())) {
                        SysGenerateFieldInfoEntity primaryInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),6);
                        primaryInfoEntity.setFieldItemName("isPrimaryKey");
                        primaryInfoEntity.setFieldItemRemark("是否为主键");
                        /**主键页面属性*/
                        primaryInfoEntity.setRequired("1");  //必填
                        primaryInfoEntity.setValueType("3"); //单选框
                        primaryInfoEntity.setDictType("yn");
                        primaryInfoEntity.setFieldItemValue(String.valueOf(sysGenerateTabColumn.getIsPrimaryKey())); //必填默认值（取数据库配置）
                        generateFieldInfoEntityList.add(primaryInfoEntity);
                    }
                    for(SysGenerateItemConfigEntity tbGenerateItemConfigEntity : tbGenerateItemConfigEntityList) {
                        SysGenerateFieldInfoEntity primaryInfoEntity = new SysGenerateFieldInfoEntity(sysGenerateTabColumn.getFieldName(), sysGenerateTabColumn.getColumnName(), sysGenerateTabColumn.getColumnComment(), "1", generateEntity.getId(),(tbGenerateItemConfigEntity.getSort()+6));
                        primaryInfoEntity.setFieldItemName(tbGenerateItemConfigEntity.getFieldName());
                        primaryInfoEntity.setFieldItemRemark(tbGenerateItemConfigEntity.getFieldRemark());
                        /**主键页面属性*/
                        primaryInfoEntity.setRequired(tbGenerateItemConfigEntity.getRequired());  //必填
                        primaryInfoEntity.setValueType(tbGenerateItemConfigEntity.getValueType());
                        primaryInfoEntity.setFieldItemValue(tbGenerateItemConfigEntity.getDefaultValue()); //必填默认值（取数据库配置）
                        primaryInfoEntity.setDictType(tbGenerateItemConfigEntity.getDictType());
                        generateFieldInfoEntityList.add(primaryInfoEntity);
                    }
                }
                generateFieldInfoService.saveBatch(generateFieldInfoEntityList);
                return Result.ok("新增成功！");
            } else {
                return Result.error("数据库表不存在！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("新增失败！");
    }


}
